// 配置对话框管理
class ConfigDialog {
    constructor() {
        this.currentStep = 1;
        this.totalSteps = 3;
        this.config = {};
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadConfig();
    }

    bindEvents() {
        // 文件夹选择
        document.getElementById('select-folder-btn').addEventListener('click', () => {
            this.selectFolder();
        });

        // AI连接测试
        document.getElementById('test-ai-btn').addEventListener('click', () => {
            this.testAIConnection();
        });

        // 导航按钮
        document.getElementById('next-btn').addEventListener('click', () => {
            this.nextStep();
        });

        document.getElementById('prev-btn').addEventListener('click', () => {
            this.prevStep();
        });

        document.getElementById('skip-btn').addEventListener('click', () => {
            this.skipConfig();
        });

        document.getElementById('start-app-btn').addEventListener('click', () => {
            this.startApp();
        });
    }

    async loadConfig() {
        try {
            this.config = await window.electronAPI.getConfig();
            this.updateUI();
        } catch (error) {
            console.error('加载配置失败:', error);
        }
    }

    updateUI() {
        // 更新AI配置输入框
        if (this.config.ai?.model) {
            document.getElementById('ai-url').value = this.config.ai.model.url || 'http://127.0.0.1:11434';
            document.getElementById('ai-model').value = this.config.ai.model.name || 'Gemma3:4b';
        }

        // 更新选中的文件夹
        if (this.config.sandboxPath) {
            document.getElementById('selected-folder').textContent = this.config.sandboxPath;
        }
    }

    async selectFolder() {
        try {
            const folderPath = await window.electronAPI.selectFolder();
            if (folderPath) {
                document.getElementById('selected-folder').textContent = folderPath;
                this.config.sandboxPath = folderPath;
            }
        } catch (error) {
            console.error('选择文件夹失败:', error);
        }
    }

    async testAIConnection() {
        const url = document.getElementById('ai-url').value;
        const model = document.getElementById('ai-model').value;
        const resultDiv = document.getElementById('ai-test-result');

        try {
            const success = await window.electronAPI.testAIConnection({
                url: url,
                name: model
            });

            if (success) {
                resultDiv.textContent = '连接成功！';
                resultDiv.className = 'success';
            } else {
                resultDiv.textContent = '连接失败，请检查配置';
                resultDiv.className = 'error';
            }
        } catch (error) {
            resultDiv.textContent = '连接测试失败: ' + error.message;
            resultDiv.className = 'error';
        }
    }

    nextStep() {
        if (this.currentStep < this.totalSteps) {
            this.currentStep++;
            this.updateStepDisplay();
        }
    }

    prevStep() {
        if (this.currentStep > 1) {
            this.currentStep--;
            this.updateStepDisplay();
        }
    }

    updateStepDisplay() {
        // 隐藏所有步骤
        for (let i = 1; i <= this.totalSteps; i++) {
            document.getElementById(`step-${i}`).style.display = 'none';
        }

        // 显示当前步骤
        document.getElementById(`step-${this.currentStep}`).style.display = 'block';

        // 更新导航按钮
        document.getElementById('prev-btn').style.display = this.currentStep > 1 ? 'block' : 'none';
        document.getElementById('next-btn').style.display = this.currentStep < this.totalSteps ? 'block' : 'none';
    }

    async skipConfig() {
        await this.saveConfig();
        this.showMainApp();
    }

    async startApp() {
        await this.saveConfig();
        this.showMainApp();
    }

    async saveConfig() {
        try {
            // 保存AI配置
            const aiUrl = document.getElementById('ai-url').value;
            const aiModel = document.getElementById('ai-model').value;

            const newConfig = {
                ai: {
                    model: {
                        name: aiModel,
                        url: aiUrl,
                        provider: 'ollama'
                    },
                    agent: {
                        enabled: true,
                        maxTokens: 4096,
                        temperature: 0.7
                    }
                },
                sandboxPath: this.config.sandboxPath
            };

            await window.electronAPI.updateConfig(newConfig);
            this.config = { ...this.config, ...newConfig };
        } catch (error) {
            console.error('保存配置失败:', error);
        }
    }

    showMainApp() {
        document.getElementById('config-dialog').style.display = 'none';
        document.getElementById('main-app').style.display = 'block';
        mainApp.init();
    }
}

// 主应用管理
class MainApp {
    constructor() {
        this.currentMember = null;
        this.config = {};
        this.tasks = [];
        this.uploadedFiles = [];
        this.monacoEditor = null;
        this.currentFile = null;
        this.currentProject = null;
        this.taskManager = null;
        this.roles = [];
    }

    init() {
        this.bindEvents();
        this.loadConfig();
        this.loadRoles();
        this.initMonacoEditor();
        this.loadFileTree();
        this.addWelcomeMessage();
        this.setupMenuEvents();
        this.initTaskManager();
    }

    bindEvents() {
        // 成员选择
        document.querySelectorAll('.member').forEach(member => {
            member.addEventListener('click', () => {
                this.selectMember(member);
            });
        });

        // 发送消息
        document.getElementById('send-btn').addEventListener('click', () => {
            this.sendMessage();
        });

        document.getElementById('message-input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });

        // 文件上传
        document.getElementById('upload-btn').addEventListener('click', () => {
            this.uploadFile();
        });

        // 配置按钮
        document.getElementById('open-config-btn').addEventListener('click', () => {
            this.openConfig();
        });

        document.getElementById('select-sandbox-btn').addEventListener('click', () => {
            this.selectSandbox();
        });

        document.getElementById('refresh-files-btn').addEventListener('click', () => {
            this.loadFileTree();
        });

        // 任务管理按钮
        document.getElementById('start-all-tasks-btn').addEventListener('click', () => {
            this.startAllExecutableTasks();
        });

        document.getElementById('reset-tasks-btn').addEventListener('click', async () => {
            try {
                await this.taskManager.reset();
                this.updateTaskStatus();
                this.addSystemMessage('任务已重置');
            } catch (error) {
                this.showError(`重置任务失败: ${error.message}`);
            }
        });

        // 面板标签切换
        document.querySelectorAll('.panel-tabs .tab').forEach(tab => {
            tab.addEventListener('click', () => {
                this.switchTab(tab);
            });
        });
    }

    setupMenuEvents() {
        // 监听主进程发送的事件
        window.electronAPI.on('project-opened', (project) => {
            this.onProjectOpened(project);
        });

        window.electronAPI.on('project-closed', () => {
            this.onProjectClosed();
        });

        window.electronAPI.on('project-saved', () => {
            this.onProjectSaved();
        });

        window.electronAPI.on('refresh-files', () => {
            this.loadFileTree();
        });
    }

    async loadConfig() {
        try {
            this.config = await window.electronAPI.getConfig();
            if (this.config.currentProject) {
                this.currentProject = this.config.currentProject;
                this.updateProjectStatus();
            }
        } catch (error) {
            console.error('加载配置失败:', error);
        }
    }

    async loadRoles() {
        try {
            this.roles = await window.electronAPI.getRoles();
        } catch (error) {
            console.error('加载角色失败:', error);
        }
    }

    initTaskManager() {
        // 初始化任务管理器
        this.taskManager = {
            getStatus: async () => await window.electronAPI.getTaskStatus(),
            getGanttData: async () => await window.electronAPI.getGanttData(),
            startTask: async (taskId) => await window.electronAPI.startTask(taskId),
            executeParallel: async (taskIds, maxConcurrent) => await window.electronAPI.executeTasksParallel(taskIds, maxConcurrent),
            getExecutableTasks: async () => await window.electronAPI.getExecutableTasks(),
            reset: async () => await window.electronAPI.resetTasks()
        };
        
        // 定期更新任务状态
        this.updateTaskStatus();
        setInterval(() => this.updateTaskStatus(), 5000);
    }

    async updateTaskStatus() {
        try {
            const status = await this.taskManager.getStatus();
            this.updateTaskUI(status);
            this.updateGanttChart(status);
        } catch (error) {
            console.error('更新任务状态失败:', error);
        }
    }

    updateTaskUI(status) {
        // 更新任务状态显示
        const taskStatusElement = document.getElementById('task-status');
        if (taskStatusElement) {
            taskStatusElement.innerHTML = `
                <div class="status-item">
                    <span class="label">总任务:</span>
                    <span class="value">${status.total}</span>
                </div>
                <div class="status-item">
                    <span class="label">待执行:</span>
                    <span class="value">${status.pending}</span>
                </div>
                <div class="status-item">
                    <span class="label">执行中:</span>
                    <span class="value">${status.running}</span>
                </div>
                <div class="status-item">
                    <span class="label">已完成:</span>
                    <span class="value">${status.completed}</span>
                </div>
                <div class="status-item">
                    <span class="label">失败:</span>
                    <span class="value">${status.failed}</span>
                </div>
            `;
        }

        // 更新任务列表
        this.updateTasksList(status.tasks);
    }

    updateGanttChart(status) {
        const ganttContainer = document.getElementById('gantt-chart');
        if (!ganttContainer) return;

        const ganttData = status.tasks.map(task => ({
            id: task.id,
            title: task.title,
            assignee: task.assignee,
            status: task.status,
            progress: task.progress,
            start: task.startedAt || task.createdAt,
            end: task.completedAt || null
        }));

        // 简单的甘特图渲染
        ganttContainer.innerHTML = ganttData.map(task => `
            <div class="gantt-item ${task.status}" data-task-id="${task.id}">
                <div class="gantt-item-header">
                    <span class="task-title">${task.title}</span>
                    <span class="task-assignee">${this.getRoleName(task.assignee)}</span>
                </div>
                <div class="gantt-item-bar">
                    <div class="progress-bar" style="width: ${task.progress}%"></div>
                </div>
                <div class="task-status">${this.getStatusText(task.status)}</div>
            </div>
        `).join('');
    }

    getRoleName(roleId) {
        const role = this.roles.find(r => r.id === roleId);
        return role ? role.name : roleId;
    }

    getStatusText(status) {
        const statusMap = {
            'pending': '待执行',
            'running': '执行中',
            'completed': '已完成',
            'failed': '失败'
        };
        return statusMap[status] || status;
    }

    selectMember(memberElement) {
        // 移除之前的选中状态
        document.querySelectorAll('.member').forEach(m => m.classList.remove('active'));
        
        // 添加选中状态
        memberElement.classList.add('active');
        this.currentMember = memberElement.getAttribute('data-role');
        
        // 更新聊天标题
        this.addSystemMessage(`已选择角色: ${this.currentMember}`);
    }

    addWelcomeMessage() {
        const welcomeMessage = {
            type: 'ai',
            content: '欢迎使用 Synapse Team！请从左侧选择一个团队成员开始对话。'
        };
        this.addMessage(welcomeMessage);
    }

    addSystemMessage(content) {
        const systemMessage = {
            type: 'system',
            content: content
        };
        this.addMessage(systemMessage);
    }

    addMessage(message) {
        const chatMessages = document.getElementById('chat-messages');
        const messageElement = document.createElement('div');
        messageElement.className = `message ${message.type}`;
        messageElement.textContent = message.content;
        chatMessages.appendChild(messageElement);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    async sendMessage() {
        const input = document.getElementById('message-input');
        const content = input.value.trim();
        
        if (!content) return;
        
        if (!this.currentMember) {
            this.addSystemMessage('请先选择一个团队成员');
            return;
        }

        // 添加用户消息
        this.addMessage({
            type: 'user',
            content: content
        });

        input.value = '';

        // 显示加载状态
        const loadingMessage = document.createElement('div');
        loadingMessage.className = 'message ai';
        loadingMessage.innerHTML = '<span class="loading"></span> AI正在思考中...';
        document.getElementById('chat-messages').appendChild(loadingMessage);

        try {
            // 调用AI
            const response = await window.electronAPI.chatWithAI(this.currentMember, content);
            
            // 移除加载消息
            loadingMessage.remove();

            if (response.type === 'task_creation') {
                // 显示任务创建消息
                this.addMessage({
                    type: 'task-creation',
                    content: response.message
                });

                // 添加任务到列表
                if (response.tasks && Array.isArray(response.tasks)) {
                    response.tasks.forEach(task => {
                        this.addTask(task);
                    });
                }
            } else {
                // 显示普通回复
                this.addMessage({
                    type: 'ai',
                    content: response.message
                });
            }
        } catch (error) {
            // 移除加载消息
            loadingMessage.remove();
            
            this.addMessage({
                type: 'ai',
                content: `抱歉，AI服务暂时不可用: ${error.message}`
            });
        }
    }

    addTask(task) {
        this.tasks.push(task);
        this.updateTasksList();
    }

    updateTasksList(tasks = null) {
        const tasksList = document.getElementById('tasks-list');
        if (!tasksList) return;
        
        const taskData = tasks || this.tasks;
        tasksList.innerHTML = '';

        taskData.forEach((task, index) => {
            const taskElement = document.createElement('div');
            taskElement.className = `task-item ${task.status}`;
            taskElement.setAttribute('data-task-id', task.id);
            
            const roleName = this.getRoleName(task.assignee);
            const statusText = this.getStatusText(task.status);
            
            taskElement.innerHTML = `
                <div class="task-header">
                    <div class="task-title">${task.title}</div>
                    <div class="task-status ${task.status}">${statusText}</div>
                </div>
                <div class="task-description">${task.description}</div>
                <div class="task-meta">
                    <span class="task-priority ${task.priority}">${task.priority}</span>
                    <span class="task-assignee">${roleName}</span>
                    <span class="task-time">${task.estimatedTime}h</span>
                </div>
                <div class="task-progress">
                    <div class="progress-bar" style="width: ${task.progress || 0}%"></div>
                </div>
                ${task.status === 'pending' ? `
                    <div class="task-actions">
                        <button class="btn-start-task" onclick="app.startSingleTask('${task.id}')">开始执行</button>
                    </div>
                ` : ''}
                ${task.status === 'completed' && task.output ? `
                    <div class="task-output">
                        <details>
                            <summary>查看输出</summary>
                            <div class="output-content">${task.output}</div>
                        </details>
                    </div>
                ` : ''}
            `;
            tasksList.appendChild(taskElement);
        });
    }

    async startSingleTask(taskId) {
        try {
            await this.taskManager.startTask(taskId);
            this.updateTaskStatus();
        } catch (error) {
            this.showError(`启动任务失败: ${error.message}`);
        }
    }

    async startAllExecutableTasks() {
        try {
            const executableTasks = await this.taskManager.getExecutableTasks();
            if (executableTasks.length === 0) {
                this.addSystemMessage('没有可执行的任务');
                return;
            }
            
            const taskIds = executableTasks.map(task => task.id);
            await this.taskManager.executeParallel(taskIds, 3);
            this.updateTaskStatus();
        } catch (error) {
            this.showError(`批量执行任务失败: ${error.message}`);
        }
    }

    async uploadFile() {
        try {
            const file = await window.electronAPI.uploadFile();
            if (file) {
                this.uploadedFiles.push(file);
                
                // 显示文件上传消息
                this.addMessage({
                    type: 'system',
                    content: `已上传文件: ${file.name} (${this.formatFileSize(file.size)})`
                });

                // 如果有选中的成员，可以询问AI分析文件
                if (this.currentMember) {
                    this.addMessage({
                        type: 'ai',
                        content: `[${this.currentMember}] 已收到文件 "${file.name}"，请告诉我您希望我如何处理这个文件。`
                    });
                }
            }
        } catch (error) {
            console.error('文件上传失败:', error);
            this.addSystemMessage('文件上传失败: ' + error.message);
        }
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    async openConfig() {
        // 重新显示配置对话框
        document.getElementById('config-dialog').style.display = 'flex';
        document.getElementById('main-app').style.display = 'none';
        configDialog.loadConfig();
    }

    async selectSandbox() {
        try {
            const folderPath = await window.electronAPI.selectFolder();
            if (folderPath) {
                this.addSystemMessage(`沙盒文件夹已更新: ${folderPath}`);
                this.loadFileTree();
            }
        } catch (error) {
            console.error('选择沙盒失败:', error);
        }
    }

    // 项目事件处理
    onProjectOpened(project) {
        this.currentProject = project;
        this.updateProjectStatus();
        this.addSystemMessage(`项目已打开: ${project.name}`);
        this.loadFileTree();
    }

    onProjectClosed() {
        this.currentProject = null;
        this.updateProjectStatus();
        this.addSystemMessage('项目已关闭');
        this.loadFileTree();
    }

    onProjectSaved() {
        this.addSystemMessage('项目已保存');
    }

    updateProjectStatus() {
        const header = document.querySelector('.app-header h1');
        if (this.currentProject) {
            header.textContent = `Synapse Team - ${this.currentProject.name}`;
        } else {
            header.textContent = 'Synapse Team';
        }
    }

    // Monaco编辑器初始化
    initMonacoEditor() {
        if (typeof require !== 'undefined') {
            require.config({ paths: { vs: 'https://unpkg.com/monaco-editor@0.45.0/min/vs' } });
            require(['vs/editor/editor.main'], () => {
                this.monacoEditor = monaco.editor.create(document.getElementById('monaco-editor'), {
                    value: '// 欢迎使用 Synapse Team 代码编辑器\n// 选择文件开始编辑',
                    language: 'javascript',
                    theme: 'vs-dark',
                    automaticLayout: true,
                    minimap: { enabled: true },
                    fontSize: 14,
                    lineNumbers: 'on',
                    roundedSelection: false,
                    scrollBeyondLastLine: false,
                    readOnly: false
                });

                // 监听内容变化
                this.monacoEditor.onDidChangeModelContent(() => {
                    this.onEditorContentChanged();
                });
            });
        }
    }

    // 编辑器内容变化处理
    onEditorContentChanged() {
        if (this.currentFile && this.monacoEditor) {
            const content = this.monacoEditor.getValue();
            // 这里可以添加自动保存功能
            console.log('文件内容已更改:', this.currentFile, content.length);
        }
    }

    // 加载文件树
    async loadFileTree() {
        try {
            const files = await window.electronAPI.getSandboxFiles();
            this.renderFileTree(files);
        } catch (error) {
            console.error('加载文件树失败:', error);
        }
    }

    // 渲染文件树
    renderFileTree(files) {
        const fileTree = document.getElementById('file-tree');
        fileTree.innerHTML = '';

        if (files.length === 0) {
            fileTree.innerHTML = '<div class="file-item">暂无文件</div>';
            return;
        }

        files.forEach(file => {
            const fileElement = this.createFileElement(file);
            fileTree.appendChild(fileElement);
        });
    }

    // 创建文件元素
    createFileElement(file) {
        const fileElement = document.createElement('div');
        fileElement.className = `file-item ${file.type}`;
        fileElement.setAttribute('data-path', file.path);
        
        const icon = file.type === 'directory' ? '📁' : this.getFileIcon(file.extension);
        const name = file.name;
        
        fileElement.innerHTML = `
            <span class="file-icon">${icon}</span>
            <span class="file-name">${name}</span>
        `;

        fileElement.addEventListener('click', () => {
            this.selectFile(file);
        });

        return fileElement;
    }

    // 获取文件图标
    getFileIcon(extension) {
        const iconMap = {
            '.js': '📄',
            '.ts': '📄',
            '.html': '🌐',
            '.css': '🎨',
            '.json': '📋',
            '.md': '📝',
            '.png': '🖼️',
            '.jpg': '🖼️',
            '.jpeg': '🖼️',
            '.gif': '🖼️',
            '.svg': '🖼️'
        };
        return iconMap[extension] || '📄';
    }

    // 选择文件
    async selectFile(file) {
        try {
            // 移除之前的选中状态
            document.querySelectorAll('.file-item').forEach(item => {
                item.classList.remove('selected');
            });

            // 添加选中状态
            const fileElement = document.querySelector(`[data-path="${file.path}"]`);
            if (fileElement) {
                fileElement.classList.add('selected');
            }

            this.currentFile = file;

            if (file.type === 'file') {
                await this.loadFileContent(file.path);
            }
        } catch (error) {
            console.error('选择文件失败:', error);
        }
    }

    // 加载文件内容
    async loadFileContent(filePath) {
        try {
            const fileData = await window.electronAPI.readFile(filePath);
            
            if (fileData.type === 'file') {
                this.renderFileContent(fileData);
            }
        } catch (error) {
            console.error('加载文件内容失败:', error);
            this.showError(`加载文件失败: ${error.message}`);
        }
    }

    // 渲染文件内容
    renderFileContent(fileData) {
        const { content, extension } = fileData;

        // 设置编辑器语言
        if (this.monacoEditor) {
            const language = this.getLanguageFromExtension(extension);
            monaco.editor.setModelLanguage(this.monacoEditor.getModel(), language);
            this.monacoEditor.setValue(content);
        }

        // 更新预览
        this.updatePreview(fileData);

        // 切换到编辑器标签
        this.switchToTab('editor');
    }

    // 根据扩展名获取语言
    getLanguageFromExtension(extension) {
        const languageMap = {
            '.js': 'javascript',
            '.ts': 'typescript',
            '.html': 'html',
            '.css': 'css',
            '.json': 'json',
            '.md': 'markdown',
            '.py': 'python',
            '.java': 'java',
            '.cpp': 'cpp',
            '.c': 'c',
            '.php': 'php',
            '.rb': 'ruby',
            '.go': 'go',
            '.rs': 'rust'
        };
        return languageMap[extension] || 'plaintext';
    }

    // 更新预览
    updatePreview(fileData) {
        const previewContent = document.getElementById('preview-content');
        const { content, extension } = fileData;

        if (['.png', '.jpg', '.jpeg', '.gif', '.svg'].includes(extension)) {
            // 图片预览
            previewContent.innerHTML = `<img src="data:image/${extension.slice(1)};base64,${btoa(content)}" alt="预览图片">`;
        } else if (extension === '.json') {
            // JSON预览
            try {
                const jsonObj = JSON.parse(content);
                previewContent.innerHTML = `<pre>${JSON.stringify(jsonObj, null, 2)}</pre>`;
            } catch (error) {
                previewContent.innerHTML = `<pre>${content}</pre>`;
            }
        } else if (extension === '.html') {
            // HTML预览
            previewContent.innerHTML = content;
        } else {
            // 文本预览
            previewContent.innerHTML = `<pre>${content}</pre>`;
        }
    }

    // 切换标签
    switchTab(tabElement) {
        const tabName = tabElement.getAttribute('data-tab');
        this.switchToTab(tabName);
    }

    // 切换到指定标签
    switchToTab(tabName) {
        // 更新标签状态
        document.querySelectorAll('.panel-tabs .tab').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');

        // 更新内容显示
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
        });
        document.getElementById(`${tabName}-tab`).classList.add('active');
    }

    // 显示错误信息
    showError(message) {
        this.addSystemMessage(message);
    }
}

// 初始化应用
let configDialog;
let mainApp;

document.addEventListener('DOMContentLoaded', () => {
    configDialog = new ConfigDialog();
    mainApp = new MainApp();
}); 